package com.leetcode.根据数据结构分类.数组;

import java.util.Arrays;

/**
 * @author: ZhouBert
 * @date: 2021/3/4
 * @description: 66. 加一
 * https://leetcode-cn.com/problems/plus-one/
 */
public class A_66_加一 {

	static A_66_加一 action = new A_66_加一();

	public static void main(String[] args) {
test1();
	}

	public static void test1() {
		int[] nums = new int[]{1, 2, 3};
		int[] res = action.plusOne(nums);
		System.out.println("res = " + Arrays.toString(res));
	}

	public int[] plusOne(int[] digits) {
		int len = digits.length;
		//进位标志
		boolean flag = true;
		int[] tempRes = new int[len];

		int i = len - 1;
		for (; i >= 0; i--) {
			if (flag) {
				//如果存在进位标志
				if (digits[i] == 9) {
					tempRes[i] = 0;
				} else {
					//一旦木有出现进位，就退出本次循环，避免多余的判断
					tempRes[i] = digits[i] + 1;
					flag = false;
					break;
				}
			}
		}
		//排除进位情况后，直接复制
		for (int j = i - 1; j >= 0; j--) {
			tempRes[j] = digits[j];
		}

		if (flag) {
			//如果仍然存在进位标志
			int[] res = new int[len + 1];
			res[0] = 1;
			for (int j = 0; j <= len; j++) {
				res[j] = tempRes[j - 1];
			}
			return res;
		}
		return tempRes;
	}
}
